package com.mlt.back.web.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/back/code")
public class Code extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //定义验证码的长宽
        int width=300;
        int height=90;
        //新建图片对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //绘制图片，根据图片对象拿到画笔对象
        Graphics2D pen = image.createGraphics();
        //绘制背景
        pen.setColor(getRandomColor());
        //绘制实心矩形框
        pen.fillRect(0,0,width,height);

        //绘制验证码字符串
        int letterNum=4;//验证码字数
        int space=20;//字母之间的距离
        int letterWidth=(width-(letterNum+1)*space)/letterNum;//计算每个字符占用的宽度

        String code="";
        Random random=new Random();
        //循环4次，每次产生一个字母
        for (int i = 0; i < letterNum; i++) {
            //随机生成一个小写字母
            int ascii=random.nextInt(26)+97;//97-122
            byte[] bs={(byte) ascii};
            String letter = new String(bs);
            code+=letter;
            pen.setColor(getRandomColor());
            pen.setFont(new Font("Gulim",Font.BOLD,70));
            pen.drawString(letter,space+(letterWidth+space)*i,height-space);
        }
        request.getSession().setAttribute("code",code);
        ImageIO.write(image,"png",response.getOutputStream());
    }

    //随机生成一种颜色
    private Color getRandomColor() {
        Random random = new Random();
        int r = random.nextInt(256);
        int b = random.nextInt(256);
        int g = random.nextInt(256);
        Color color = new Color(r, g, b);
        return color;
    }
}
